<?php
session_start();
ob_start();
include("db_conn_new.inc");
include("iDecision.php");
date_default_timezone_set("Australia/Sydney");
$date = date("Y-m-d");
//exit;
$count_number_cilent=0; 

if($emailaddress !=''){
	$query = mysql_query("SELECT COUNT(*) AS num FROM `client_logininfo` WHERE `email_address` = '".$emailaddress."'");
	$count_number_cilent = mysql_fetch_assoc($query);
}
if ($count_number_cilent['num'] > 0)
{
	 $_SESSION['ERROR'] = 'Already registered with this mail id';
	header('location:../apply-now.php');
	exit;
}
else
{
	mysql_query("SET AUTOCOMMIT=0");
	mysql_query("START TRANSACTION");

	unset($_SESSION["ERROR"]);

	if($finalstatusByDecision=='Pass')
		$app_result='1.1 Await documents 1';	
	else 
		$app_result='1.5 Not eligible';
	
	$app_insert_qry = "INSERT INTO crm_application (deletedFlag,app_result, Loan_No,Folder,NoInApplication,OfferedAmount,DesiredAmount,amountMoto,
amoutProperties,TextAwaitDoc,PurposeSummary,Memo,LenderID,OutSrcLenderVal,ReferrerID,ReferrerVal,CreatedDate,EditDate,comesfrom,securities,IsUSB,
IsCarOwner,status,MC_process,CreatedTime,mc_preferred_loan_period,mc_ipaddress,mc_income_status,mc_asset_status,mc_credit_status,mc_final_status,
mc_ClientUpdateTime,mc_purposeType,mc_OtherPurpose,mc_Update_Time,mc_agreement,mc_browser,mc_referrer_company,mc_referrer_email,loanpurposereason,
`filledout`,`prevclient`,`purposedetail`,`boardingfee`,`livingfee`,`totalincome`,`totalexpense`,`totalexpensecorrect`,`disposableincome`,`ELA`,
`formviewnotice`,`whyus`,`timecost`,`preappcode`)
values
('0','".$app_result."','','','1','".$loanamount."','".$loanamount."','','','None doc','SACC','','0','','0','',NOW(),NOW(),'MaxCash','','No','0','opening',
'Waitingverify',CURTIME(),'".$term."','".$mc_ipaddress."','','','','".$finalstatusByDecision."',CURTIME(),'','".$mc_OtherPurpose."',NOW(),
'".$mc_agreement."','".$mc_browser."','','','".$purposeofloan."','','','','','','','','','','','','','','')";
	
	if(!$sql1 = mysql_query($app_insert_qry))
		echo mysql_error();

	$app_id=mysql_insert_id();
	
	

	if($title=='Ms'||$title=='Miss'||$title=='Mrs')
		$gender='female';
	else if($title=='Mr'||$title=='Dr'||$title=='Other')
		$gender='male';
	else
		$gender='';
        
	$residencelength=NULL;	
	if($residenceperiod=='1 month')
	{
		$residenceperiod='Month/s';
		$residencelength='1';
	}
	else if($residenceperiod=='2 months')
	{
		$residenceperiod='Month/s';
		$residencelength='2';
	}
	else if($residenceperiod=='3 months')
	{
		$residenceperiod='Month/s';
		$residencelength='3';
	}
	else if($residenceperiod=='less than 1 month')
	{
		$residenceperiod='Month/s';
		$residencelength='less than 1';
	}
	else if($residenceperiod=='4 to 6 months')
	{
		$residenceperiod='Month/s';
		$residencelength='4 to 6';
	}
	else if($residenceperiod=='7 months to 1 year')
	{
		$residenceperiod='Month/s';
		$residencelength='7 to 12';
	}
	else if($residenceperiod=='1 year to 2 years')
	{
		$residenceperiod='Year/s';
		$residencelength='1 to 2';
	}
	else if($residenceperiod=='more than 2 years')
	{
		$residenceperiod='Year/s';
		$residencelength='more than 2';
	}
		
	$street = $street.','.$streettype;
	$contact_sql = "INSERT INTO `crm_contact`
(`FirstName`,`MiddleName`,`SurName`,`Title`,`Gender`,`Mobile`,`HomePhone`,`Email`,`DriverLicense`,`Citizenship`,`DateBirth`,`StreetNo`,`Street`,
`Suburb`,`State`,`PostCode`,`ResidencePeriod`,`ResidenceLength`,`Dependant`,`app_ResidentialStatus`,`app_number`,`app_id`,`NumberFromAppinfo`,`Memo`,
`EditDate`,`DupwithContact`,`deletedFlag`,`Role`,`Relationship`,`WorkPhone`,`FaxNumber`,`secondEmailAddress`,`PostalAddress`,`IncomeType`,
`SelfEmpTypeofEntity`,`SelfEmpBusinessName`,`SelfEmpABN`,`SelfEmpNatureofBusiness`,`SelfEmpPhone`,`SelfEmpAddress`,`KinsName`,`KinsRelationship`,
`KinsContactNumber`,`Notes`,`EmpEmployer`,`EmpOccupation`,`EmpJobPosition`,`EmpEmployerPhone`,`EmpContactPerson`,`EmpWorkAddress`,`comesfrom`,
`Unsubscribe_Ad`,`CreateDate`,`Sacc_accountlock`)
VALUES
('".$firstname."','".$middlename."','".$surname."','".$title."','".$gender."','".$mobile."','".$phone."','".$emailaddress."','',
'".$citizenship."',STR_TO_DATE('".$dateofbirth."', '%d/%m/%Y'),'".$streetNo1."','".$ResidentialAddress1."','".$suburb."','".$state."',
'".$postcode."','".$residenceperiod."','".$residencelength."','".$numberofdependant."','".$residentialstatus."',
NULL,".$app_id.",NULL,'',NOW(),NULL,'0','','','','','','','','','','','','','','','','','','','','','','','','MaxCash','0',NOW(),'0')";

	if(!$sql2=mysql_query($contact_sql)){
		echo mysql_error();
		exit;
	}		
		
	$Contact_Id=mysql_insert_id();
	
	$emp_sql = "INSERT INTO crm_employment (app_id,CurrentContact_id,OriginalContact_id,employment_status,employment_type,employment_occupation,
            employer_name,employer_phone,CreatedDate,EditDate,Comesfrom)values
(".$app_id.",".$Contact_Id.",".$Contact_Id.",'','".$typeofemployment."','".$titleinoccupation."','".$businessname."','".$workphone."',
  NOW(),NOW(),'MaxCash')";
	if(!$sql3=mysql_query($emp_sql)){
		echo mysql_error();
		exit;
	}

	$income_sql = "INSERT INTO crm_income (app_id,CurrentContact_id,OriginalContact_id,income_aftertax,income_aftertax_period,income_total,
            CreatedDate,EditDate,Comesfrom)Values 
(".$app_id.",".$Contact_Id.",".$Contact_Id.",'".$incomeaftertax."','".$incomeaftertax1period."','0',NOW(),NOW(),'MaxCash')";
	if(!$sql4=mysql_query($income_sql)){
		echo mysql_error();
		exit;
	}

	$credit_sql = "INSERT INTO crm_applicationcredit (app_id,CurrentContact_id,OriginalContact_id,credit_hardship,credit_gambling,
            credit_claims,credit_history,credit_outstanding,credit_dischargedate,credit_discharge,CreatedDate,EditDate,
            Comesfrom,WhyChooseMF,ExistingClient)values
(".$app_id.",".$Contact_Id.",".$Contact_Id.",'".$hardship."','".$Gambling."','".$loaninlasttwomonth."','".$credithistory."',
'".$totaloutstanding."','".$dateofdischarge."','".$defaultafterdischarge."',NOW(),NOW(),'MaxCash','".$whychoosemf."','".$existingclient."')";

	if(!$sql5=mysql_query($credit_sql)){
		echo mysql_error();
		exit;
	}

	$liab_sql = "INSERT INTO `crm_liabilities`(`app_id`,`CurrentContact_id`,`OriginalContact_id`,`liabilities_type`,`liabilities_owing`,
            `liabilities_loanrepayment_payment`,`liabilities_loanrepayment_paymentperiod`,`liabilities_creditcard_payment`,
            `liabilities_creditcard_paymentperiod`,`liabilities_boardingrentingfee_payment`,`liabilities_boardingrentingfee_paymentperiod`,
            `liabilities_livingexpenses_payment`,`liabilities_livingexpenses_paymentperiod`,`liabilities_bank`,`CreatedDate`,`EditDate`,`Comesfrom`)
VALUES
(".$app_id.",".$Contact_Id.",".$Contact_Id.",'','','".$liabilitiesloanrepaymentpayment."','".$loanrepaymentperiod."',
'".$liabilitiescreditcardpayment."','".$creditcardpaymentperiod."','".$liabilitiesboardingrentingfeepayment."','".$boardingrentingperiod."',
'".$liabilitieslivingexpensespayment."','".$livingexpensesperiod."','',NOW(),NOW(),'MaxCash')";
	
	if(!$sql6=mysql_query($liab_sql)){
		echo mysql_error();
		exit;
        }

	$login_sql = "INSERT INTO `client_logininfo`
(`CurrentContact_id`,`OriginalContact_id`,`display_name`,`email_address`,`password`,`v_email`,`status`,`CreatedDate`,`EditDate`,`Comesfrom`)VALUES
(".$Contact_Id.",".$Contact_Id.",'".$firstname."','".$emailaddress."','".md5($loginpassword)."','0','1',NOW(),NOW(),'MaxCash')";

	if(!$sql7=mysql_query($login_sql)){
		echo mysql_error();
		exit;
	}

	$history_sql = "INSERT INTO `crm_history`(`app_id`,`HistoryDate`,`HistoryTime`,`Action`,`Operator`,`Description`)
VALUES( ".$app_id.",NOW(),CURTIME(),'Apply','".$firstname."','".$firstname." Submit new application from website')";

	if(!$sql8=mysql_query($history_sql)){
		echo mysql_error();
		exit;
	}

	$app_contact_sql = "INSERT INTO `crm_applicationcontact`
(`app_id`,`ContactID`,`NoInApplication`,`CombineApp`,`deletedFlag`)
VALUES(".$app_id.",".$Contact_Id.",'1','','0')";

	if(!$sql9=mysql_query($app_contact_sql)){
		echo mysql_error();
		exit;
	}

	$mcform_sql = "INSERT INTO `form_mc`
(`deletedFlag`, `OfferedAmount`, `DesiredAmount`, `PurposeSummary`,`LenderID`, `OutSrcLenderVal`, `ReferrerID`, `ReferrerVal`, `status`,
 `MC_process`, `mc_preferred_loan_period`, `mc_ipaddress`, `mc_income_status`, `mc_asset_status`, `mc_credit_status`, `mc_final_status`,
 `mc_ClientUpdateTime`, `mc_purposeType`, `mc_OtherPurpose`, `mc_Update_Time`, `mc_agreement`, `mc_browser`, `mc_referrer_company`,
 `mc_referrer_email`, `FirstName`, `MiddleName`, `SurName`, `Title`, `Gender`, `Mobile`, `HomePhone`, `Email`, `DriverLicense`, `Citizenship`,
 `DateBirth`, `StreetNo`, `Street`, `Suburb`, `State`, `PostCode`, `ResidencePeriod`, `ResidenceLength`, `Dependant`, `app_ResidentialStatus`,
 `WorkPhone`, `FaxNumber`, `Email1`, `secondEmailAddress`, `PostalAddress`, `boardingwith_name`,`Application_Memo`,`Contact_Memo`,
`viewtemplatepath`,`CreatedDate`,`EditDate`,`credit_hardship`,`credit_gambling`,`credit_claims`,`credit_history`,`credit_outstanding`,
`credit_dischargedate`,`credit_discharge`,`employment_status`,`employment_type`,`employment_occupation`,`employer_name`,`employer_phone`,
`income_aftertax`,`income_aftertax_period`,`income_centrelink`,`income_other`,`income_other_period`,`income_rental`,`income_total`,
`OtherIncomeSpecify`,`liabilities_type`,`liabilities_owing`,`liabilities_loanrepayment_payment`,`liabilities_loanrepayment_paymentperiod`,
`liabilities_creditcard_payment`,`liabilities_creditcard_paymentperiod`,`liabilities_boardingrentingfee_payment`,
`liabilities_boardingrentingfee_paymentperiod`,`liabilities_livingexpenses_payment`,`liabilities_livingexpenses_paymentperiod`,`liabilities_bank`)
VALUES
('0', '".$loanamount."', '".$loanamount."', 'SACC', '0', '', '0', '', 'opening', 'Waitingverify', '".$term."', '".$mc_ipaddress."', '".$IncomeStatus."', '', '".$CreditStatus."', '".$finalstatusByDecision."', CURTIME(), '', '".$purposeofloan."', '".$date."', '".$mc_agreement."', '".$mc_browser."', '', '', '".$firstname."',
 '".$middlename."', '".$surname."', '".$title."', '".$gender."', '".$mobile."', '".$phone."', '".$emailaddress."', '', '".$citizenship."',
 STR_TO_DATE('".$dateofbirth."', '%d/%m/%Y'), '".$streetNo1."', '".$ResidentialAddress1."', '".$suburb."', '".$state."', '".$postcode."',
 '".$residenceperiod."', '".$residencelength."', '".$numberofdependant."', '".$residentialstatus."', '', '', '', '', '', '', '', '', '',
 NOW(), NOW(), '".$hardship."', '".$Gambling."','".$loaninlasttwomonth."','".$credithistory."','".$totaloutstanding."','".$dateofdischarge."',
'".$defaultafterdischarge."','','".$typeofemployment."','".$titleinoccupation."','".$businessname."','".$workphone."','".$incomeaftertax."',
'".$incomeaftertax1period."',NULL,NULL,'','','0','','','','".$liabilitiesloanrepaymentpayment."','".$loanrepaymentperiod."',
'".$liabilitiescreditcardpayment."','".$creditcardpaymentperiod."','".$liabilitiesboardingrentingfeepayment."','".$boardingrentingperiod."',
'".$liabilitieslivingexpensespayment."','".$livingexpensesperiod."','')";
	
	if(!$sql12=mysql_query($mcform_sql)){
		echo mysql_error();
		exit;
	}

	$form_id = mysql_insert_id();
	
	$app_form_sql = "INSERT INTO `crm_applicationappform`(`ApplicationId`,`AppFormId`,`ComesFrom`)VALUES('".$app_id."','".$form_id."','MaxCash')";

	if(!$sql13 = mysql_query($app_form_sql)){
		echo mysql_error();
		exit;
	}
	
include("etemp.php");
 
	if($finalstatusByDecision=='Pass')
	{
		$sql10=mysql_query("INSERT INTO `sacc_verificationstatus`
(`app_id`,`sms_attempts`,`sms_status`,`idcheck_attempts`,`idcheck_status`,`bankretrieve_attempts`,`bankretrieve_status`,`payslip_status`,`CreatedDate`,
`UpdatedDate`,`MC_apply`,`creditehistory`,`incomeexpense`,`phoneverification`,`contractprepared`,`contractsigned`,`fundtransferred`)VALUES
('".$app_id."','1','0','1','0','1','0','0',NOW(),NOW(),'','0','0','0','0','0','0')");
		//if(!$sql10 = mysql_query($app_form_sql)){
		//echo mysql_error();
		//exit;
		//}
				
		$sql11=mysql_query("INSERT INTO `client_loginhistory`
(`CurrentContact_id`,`OriginalContact_id`,`display_name`,`email_address`,`LoginDate`,`LoginTime`,`LoginIP`,`LoginBrowser`,`Comesfrom`)
VALUES(".$Contact_Id.",".$Contact_Id.",'".$firstname."','".$emailaddress."',DATE(NOW()),CURTIME(),'".$mc_ipaddress."','".$mc_browser."','MaxCash')");

		$_SESSION['display_name'] = $firstname;
		$_SESSION['app_email_addr'] = $emailaddress;
		$_SESSION['applicant_id'] = $Contact_Id;  
		$_SESSION['CurrentContact_id'] = $Contact_Id;
		$_SESSION['app_id'] = $app_id;	
		
		if ($sql1 and $sql2 and $sql3 and $sql4 and $sql5 and $sql6 and $sql7 and $sql8 and $sql9 and $sql10 and $sql11) {
			
			if(isset($_SESSION['fb_user_id']) && $_SESSION['fb_user_id'] != 0) {
				
			$fbuser_update = "UPDATE crm_social_authentication SET OriginalContact_id =".$Contact_Id." WHERE id =".$_SESSION['fb_user_id'];
			mysql_query($fbuser_update);
			}
			
			mysql_query("COMMIT");
			
			$msgSubject = "Email Verification From Maxcash";			 
			$msgContent = "Hello World.";
			$msgContent = $html;
			sentEmail($emailaddress, $msgContent, $msgSubject);
			//sendSMS($mobile);			
			//header('Location: ../account/index.php');
			$afterpage="http://maxcash.com.au/includes/complete-pass.php?ela=".$ela;
			header("Location: " .$afterpage);
			//echo ($finalstatusByDecision); 
			exit;
		} else {       
    		mysql_query("ROLLBACK");
			header('location:../apply-now.php');
			exit;
		}}
		else{
		if ($sql1 and $sql2 and $sql3 and $sql4 and $sql5 and $sql6 and $sql7 and $sql8 and $sql9) {
			
			if(isset($_SESSION['fb_user_id']) && $_SESSION['fb_user_id'] != 0) {
				
			$fbuser_update = "UPDATE crm_social_authentication SET OriginalContact_id =".$Contact_Id." WHERE id =".$_SESSION['fb_user_id'];
			mysql_query($fbuser_update);
			}
			
    		mysql_query("COMMIT");
			if($app_result=='1.5 Not eligible'){
			$afterpage="http://maxcash.com.au/includes/complete-decline.php?LoanAmount=".$loanamount."&FirstName=".$firstname."&MiddleName=".$middlename."&LastName=".$surname."&Title=".$title."&Citizenship=".$citizenship."&DOB=".$dateofbirth."&Dependant=".$numberofdependant."&Address=".$residentialaddress."&ResidentialStatus=".$residentialstatus."&Email=".$emailaddress."&Mobile=".$mobile."&HomePhone=".$phone."&Purpose=".$purposeofloan."&EmploymentStatus=".$typeofemployment."&JobTitle=".$titleinoccupation."&EmployerName=".$businessname."&WorkPhone=".$workphone."&WorkIncome=".$incomeaftertax."&WorkIncomePeriod=".$incomeaftertax1period."&HardShip=".$hardship."&CreditHistory=".$credithistory."&OutstandingValue=".$totaloutstanding."&DischargeDate=".$dateofdischarge."&DefaultAfterDischarge=".$defaultafterdischarge;
			header("Location: " .$afterpage);exit;
			} 
		} else {        	
    		mysql_query("ROLLBACK"); 
			exit;
			header('location:../apply-now.php');
		}}
}

function sentEmail($to, $msg, $sub)
{
	//$subject = 'Application Form technical error report';
	//$to = 'MFtesting1234@hotmail.com';
	//$to1="cashlogin@gmail.com";
	//$to = 'infaario@gmail.com';
	
	require_once '../swift-mailer/lib/swift_required.php';
	
	$transport = Swift_SmtpTransport::newInstance('tls://mail.maxcash.com.au', 465)
  ->setUsername('loans@maxcash.com.au')
  ->setPassword('Mc456789');
  	$mailer = Swift_Mailer::newInstance($transport);

// Create a message
	$message = Swift_Message::newInstance($sub)
  ->setFrom(array('no-reply@maxcash.com.au' => 'Max Cash'))
  ->setTo(array($to))
  ->setCc('infaario@gmail.com')
  ->setContentType("text/html")
  ->setBody($msg);

	// Send the message
	$result = $mailer->send($message);
	if($result)
	{
		return true;				
	}
	else
	{
		return false;
	} 		
	
	/*$message = $msg;
	$subject = $sub;	
	if($msg){
		
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		$headers .= 'From: Email Verification <no-reply@maxcash.com.au> ' . "\r\n";
		$headers .= 'Cc: mflogin6@gmail.com' . "\r\n";
		//$headers .= 'Cc: infaario@gmail.com' . "\r\n";    		
		//$send_contact =  mail($to,$subject,$message,$headers,"-f contact@Max Cash.com.au"); 
		$send_contact =  mail($to,$subject,$message,$headers); 
		if($send_contact)
		{
			return true;				
		}
		else
		{
			return false;
		} 			
	}*/
}

function sendSMS($mobile)
{
	require("sms/smsconn.php");
	$monumber = $mobile;
	//$pin_code = generatePassword($length = 8);
	$smscontent = "Loan Update: Your Loan has been Pre-Approved. For verification purposes, please login to your account manager and upload supporting documents. Max Cash";
	
	$si = new SmsInterface (false, false);
	$si->addMessage ($mobile, $smscontent);

	if (!$si->connect ($username, $password, true, false))
	    $sms_emsg = "failed. Could not contact server.\n";
	elseif (!$si->sendMessages ()) 
	{
	    $sms_emsg = "failed. Could not send message to server.\n";
	    if ($si->getResponseMessage () !== NULL)
			$sms_emsg = "<BR>Reason: " . $si->getResponseMessage () . "\n";
	} 
	else
	    $sms_emsg = true;
	
	//return $si->getResponseMessage();
	return $sms_emsg;
}
ob_flush();
?>

